package com.coolingme.notandor.expression.nonterminal;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.StrSplitter;
import com.coolingme.notandor.IExpression;
import com.coolingme.notandor.expression.operator.OrOperator;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 或(|) 非终结符表达式
 *
 * @author wangyue
 * @date 2022/12/25 11:34
 */
@Slf4j
public class OrExpression implements IExpression {

    /**
     * 或逻辑的操作表达式列表
     */
    private List<IExpression> orExpressionList = new ArrayList();

    public OrExpression(List<IExpression> expressions) {
        // 根据或操作符分割
        int[] orIndexArray = ListUtil.indexOfAll(expressions, OrOperator.getInstance()::equals);

        // 有或符号，保存或前后的表达式
        if (orIndexArray.length > 0) {
            int start = 0;
            int end;
            for (int orIndex : orIndexArray) {
                end = orIndex;
                // 分割或前后的表达式
                List<IExpression> expressionList = ListUtil.sub(expressions, start, end);
                this.orExpressionList.add(new AndExpression(expressionList));
                start = orIndex + 1;
            }
            end = expressions.size();
            List<IExpression> expressionList = ListUtil.sub(expressions, start, end);
            this.orExpressionList.add(new AndExpression(expressionList));
        } else {
            // 没有或符号，所有表达式作为并连接
            this.orExpressionList.add(new AndExpression(expressions));
        }

    }

    public OrExpression(String strOrExpression) {
        List<String> strExpressionList = StrSplitter.splitByRegex(strOrExpression, "\\|", -1, true, true);
        for (String strExpression : strExpressionList) {
            this.orExpressionList.add(new AndExpression(strExpression));
        }
    }

    @Override
    public Boolean interpret(String content) {
        for (IExpression expression : this.orExpressionList) {
            // 或的语法为有一个是true，就返回true
            if (expression.interpret(content)) {
                return true;
            }
        }
        // 全部是false才返回false
        return false;
    }


}
